using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using EFProviderWrapperToolkit;

namespace EFMetaProvider
{
    public class EFMetaConnection : DbConnectionWrapper
    {
		public DataTable SchemaTable;
        public EFMetaConnection(): this(null)
        {
        }

        public EFMetaConnection(DbConnection wrappedConnection)
        {
            WrappedConnection = wrappedConnection;
        }

        protected override string DefaultWrappedProviderName
        {
            get { return EFMetaProviderConfiguration.DefaultWrappedProvider; }
        }

        protected override DbProviderFactory DbProviderFactory
        {
            get { return EFMetaProviderFactory.Instance; }
        }

    	public ColumnMetadata[] Metadata
    	{
    		get
    		{
    			var rows = SchemaTable.Rows;
    			var result = new List<ColumnMetadata>();
				// ColumnOrdinal,IsUnique,IsKey,BaseServerName,BaseCatalogName,BaseColumnName,BaseSchemaName,BaseTableName,DataType,AllowDBNull,ProviderType,IsAliased,IsExpression,
				// IsIdentity,IsAutoIncrement,IsRowVersion,IsHidden,IsLong,IsReadOnly,ProviderSpecificDataType,DataTypeName,XmlSchemaCollectionDatabase,XmlSchemaCollectionOwningSchema,
				// XmlSchemaCollectionName,UdtAssemblyQualifiedName,NonVersionedProviderType,IsColumnSet
    			var colName = SchemaTable.Columns["ColumnName"];
    			var colSize = SchemaTable.Columns["ColumnSize"];
				var numericPrecision = SchemaTable.Columns["NumericPrecision"];
				var numericScale = SchemaTable.Columns["NumericScale"];
				var allowDbNull = SchemaTable.Columns["AllowDBNull"];
				foreach (DataRow row in rows)
    			{
    				var col = new ColumnMetadata
    				{
    					ColumnName = (string) row[colName],
    					ColumnSize = (int) row[colSize],
    					NumericPrecision = row.IsNull(numericPrecision) ? (int?) null : (int) row[numericPrecision],
    					NumericScale = row.IsNull(numericScale) ? (int?) null : (int) row[numericScale],
    					IsNullable = (bool) row[allowDbNull]
    				};
    				result.Add(col);		
    			}
    			return result.ToArray();
    		}
    	}
    }
}
